/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.openfire;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.packet.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.bsl.JsonMapper;
import com.foreveross.bsl.MessageStatistics;
import com.foreveross.bsl.PushMessage;

/**
 * xxx
 *
 * @author Wangyi
 * @version v1.0
 *
 * @date 2013-12-11
 *
 */
public class ReceiveStatisticMessageListener implements MessageListener {
	
	private final static Logger log = LoggerFactory.getLogger(ReceiveStatisticMessageListener.class);
	
	private final MessageStatistics msgStat;
	
	public ReceiveStatisticMessageListener(MessageStatistics msgStat){
		this.msgStat=msgStat;
	}

	@Override
	public void processMessage(Chat chat, Message message) {
		String msgBody=message.getBody();
		log.debug("msg body: {}", msgBody);
		try {
			PushMessage msg=this.parseMessageBody(msgBody);
			msgStat.count(msg);
			log.debug("{} -> {}: {}", message.getFrom(), message.getTo(), msg.getTitle());
			this.handlePushMessage(msg);
		} catch (Exception e) {
			log.error("parser message error, message:{}", msgBody);
		} 
	}
	
	protected void handlePushMessage(PushMessage pmsg){
		
	}
	
	private PushMessage parseMessageBody(String msgBody){
		PushMessage msg=JsonMapper.NON_EMPTY_JSON_MAPPER.fromJson(msgBody, PushMessage.class);
		if(msg.getSendTime()==null){
			msg.setSendTime(this.tryParseSendTimeInTitle(msg.getTitle()));
		}
		msg.setArrivedTime(new Date());
		return msg;
	}
	
	private Date tryParseSendTimeInTitle(String title){
		String time=StringUtils.split(title, '@')[0].trim();
		try {
			return new Date(Long.parseLong(time));
		} catch (NumberFormatException e) {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				return sdf.parse(time);
			} catch (ParseException e1) {
			}
		}
		return null;
	}
	
}
